package com.example.miscontactos;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.miscontactos.Entidades.HistorialClass;

import BaseDeDatos.AccesoABaseDeDatos;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TweetsActivity extends Activity 
{

	private long id = 0;
	private static String CONTACTO_ID = "contactoId";
	private LinearLayout contentTweets;
	private String twitterUser = ""; 
	Intent starterIntent;
	private String TAB_SELECCIONADO = "tab_seleccionado";
	//private Boolean esRespuestaDialogoOk = true;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tweets);
		
		id = this.getIntent().getExtras().getLong(CONTACTO_ID);
		starterIntent = getIntent();
				
		cargarDatos();				
	}
	
	private void cargarDatos()
	{
		Cursor cur = null;
		if (isOnline())
		{
			cur = AccesoABaseDeDatos.obtenerTweeterUser(this, id);			
			getNombreTwiter(cur);
			if(!twitterUser.equalsIgnoreCase(""))
				conectarTwiter();
			else
				return;
		}
		else
		{
			Toast toast = Toast.makeText(this, getResources().getString(R.string.no_internet_conection), Toast.LENGTH_SHORT);
			toast.show();
		}	
	}
	
	private void getNombreTwiter(Cursor cur)
	{
		if(cur.getCount() > 0)
		{
			cur.moveToFirst();
			twitterUser = cur.getString(0);			
		}
		else
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        builder.setTitle(getResources().getString(R.string.titulo_twiter_alert_dialog));
	 
	        final EditText input = new EditText(this);
	        input.setHint(getResources().getString(R.string.nombre_usuario_twiter_alert_dialog));
	        builder.setView(input);
	 
	        builder.setPositiveButton(getResources().getString(R.string.aceptar_alert_dialog), new DialogInterface.OnClickListener() 
	        {
	 			@Override
	            public void onClick(DialogInterface dialog, int whichButton) 
	            {
	            	twitterUser = input.getText().toString();
	            	AccesoABaseDeDatos.registrarTwitterUserName(TweetsActivity.this, id, twitterUser);
	            	TweetsActivity.this.conectarTwiter();
	            	//esRespuestaDialogoOk = true;
	            }
	        });
	 
	        builder.setNegativeButton(getResources().getString(R.string.cancelar_alert_dialog), new DialogInterface.OnClickListener() 
	        {
	            @Override
	            public void onClick(DialogInterface dialog, int which) 
	            {
	                //esRespuestaDialogoOk = false;
	            	return;
	            }
	        });
	 
	        builder.show();
		}
	}

	private void conectarTwiter()
	{
		contentTweets = (LinearLayout) this.findViewById(R.id.tweets);
		String queryTwitter = "from:" + twitterUser + "%20OR%20to:" + twitterUser;
		new DoConection().execute("http://search.twitter.com/search.json?q=" + queryTwitter);		
	}
	
	private boolean isOnline() 
	{
	    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) 
	    {
	        return true;
	    }
	    return false;
	}

	/*@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_tweets, menu);
		return true;
	}*/
	
	class DoConection extends AsyncTask<String, View, String> 
	{
		protected String doInBackground(String... urls) 
		{
			HttpURLConnection urlConnection = null;
						
			JSONObject json;
			JSONArray json2;
			try 
			{
				URL url = new URL(urls[0]);
				urlConnection = (HttpURLConnection) url.openConnection();
				BufferedInputStream in = new BufferedInputStream(
						urlConnection.getInputStream());
				
				json = new JSONObject(readStream(in));
				json2 = json.getJSONArray("results");
				if(json2.length() != 0)
				{
					for(int i = 0; i <= 10 ; i++)
					{
						JSONObject tweet = json2.getJSONObject(i);
						View v = LayoutInflater.from(TweetsActivity.this).inflate(R.layout.fila_tweeter, null,false);
						String urlImageUser = tweet.getString("profile_image_url");
						URL thumb_u = new URL(urlImageUser);
					    Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
						ImageView userView = (ImageView) v.findViewById(R.id.imageUser);
						userView.setImageDrawable(thumb_d);
						TextView userText = (TextView) v.findViewById(R.id.user);
						String userName = tweet.getString("from_user_name");
						String date = tweet.getString("created_at");
						String[] parts = date.split("\\+");
						userText.setText(userName + " - " + parts[0]);
						TextView tweetText = (TextView) v.findViewById(R.id.tweetContent);
						tweetText.setText(tweet.getString("text"));
						this.publishProgress(v);
					}
				}
				else
				{
					View v = LayoutInflater.from(TweetsActivity.this).inflate(R.layout.fila_tweeter, null,false);
					TextView userText = (TextView) v.findViewById(R.id.user);
					userText.setTextSize(20);
					userText.setText(getResources().getString(R.string.no_twitter_content));
					ImageView userView = (ImageView) v.findViewById(R.id.imageUser);
					userView.setVisibility(View.GONE);
					TextView tweetText = (TextView) v.findViewById(R.id.tweetContent);
					tweetText.setVisibility(View.INVISIBLE);
					this.publishProgress(v);
				}
				return readStream(in);
			}
			catch (Exception e) 
			{
				e.printStackTrace();
				return "{}";
			} finally 
			{
			}
		}

		public String readStream(BufferedInputStream in) throws IOException 
		{
			StringBuffer stream = new StringBuffer();
			byte[] b = new byte[8192];
			for (int n; (n = in.read(b)) != -1;) {
				stream.append(new String(b, 0, n));
			}
			return stream.toString();
		}

		protected void onProgressUpdate(View... progress) 
		{
			contentTweets.addView(progress[0]);
		}

		protected void onPostExecute(String result) 
		{
		}
	}

}
